/*******************************************************************************
 * Copyright (c) 2012, G. Weirich and Elexis
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    G. Weirich - initial implementation
 *******************************************************************************/

package ch.elexis.easy.ui.widgets;

import org.eclipse.core.databinding.Binding;
import org.eclipse.core.databinding.DataBindingContext;
import org.eclipse.core.internal.databinding.validation.ValidatedObservableValue;
import org.eclipse.jface.databinding.swt.SWTObservables;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Text;

import ch.elexis.core.data.IAttribute;
import ch.elexis.core.data.IPersistentObject;
import ch.elexis.core.databinding.PersistentObjectObservableValue;

/**
 * An input field that is bound to an attribute of IPersistentObject
 * @author gerry
 *
 */
public class BoundField {
	Control widget;
	PersistentObjectObservableValue pw;
	DataBindingContext dbc;
	Binding binding;
	IAttribute field;
	
	/**
	 * Constructor
	 * @param parent parent composite
	 * @param field attribute to link
	 */
	public BoundField(Composite parent, IAttribute field){
		widget = createWidget(parent);
		dbc = new DataBindingContext(SWTObservables.getRealm(Display.getCurrent()));
		this.field = field;
	}
	
	/**
	 * Set a new Object to connect
	 * @param obj
	 */
	public void setObject(IPersistentObject obj){
		if (binding != null) {
			dbc.removeBinding(binding);
			binding.dispose();
			binding = null;
		}
		if (obj != null) {
			pw = new PersistentObjectObservableValue(obj, field);
			binding = dbc.bindValue(SWTObservables.observeText(widget), pw);
		}
	}
	
	protected Control createWidget(Composite parent){
		Control ret = new Text(parent, SWT.BORDER);
		return ret;
	}
	
	public Control getWidget(){
		return widget;
	}
	
}
